package com.zhongke.cotrun.controller;

import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.zhongke.cotrun.common.annotation.SysLog;
import com.zhongke.cotrun.common.util.APIResponse;
import com.zhongke.cotrun.common.util.AddIntegralUtils;
import com.zhongke.cotrun.model.pojo.CommonConfig;
import com.zhongke.cotrun.model.pojo.NeedInfo;
import com.zhongke.cotrun.model.pojo.Region;
import com.zhongke.cotrun.model.pojo.UserInfo;
import com.zhongke.cotrun.model.pojo.UserInforCompany;
import com.zhongke.cotrun.model.pojo.WxSysDict;
import com.zhongke.cotrun.model.resultpackage.CodeMsg;
import com.zhongke.cotrun.service.CommonConfigService;
import com.zhongke.cotrun.service.MessageService;
import com.zhongke.cotrun.service.NeedInfoService;
import com.zhongke.cotrun.service.RegionService;
import com.zhongke.cotrun.service.UserInfoService;
import com.zhongke.cotrun.service.WxSysDictService;
import com.zhongke.cotrun.service.WxUserInfoService;
import com.zhongke.cotrun.shiro.sys.shiro.ShiroUtils;

import io.swagger.annotations.*;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.constraints.NotNull;
/**
 * @Description: 用户需求信息
 * @Author: songjing
 * @Date:   2020-03-18
 * @Version: V1.0
 */
@Api(tags = "用户需求信息相关接口")
@RestController
@RequestMapping("/needInfo")
@Validated
public class NeedInfoController {
    @Autowired
    AddIntegralUtils addIntegralUtils;
    @Autowired
    NeedInfoService needInfoService;
    @Autowired
    WxSysDictService wxSysDictService;
    @Autowired
    WxUserInfoService wxUserInfoService;
    @Autowired
    MessageService messageService;
    @Autowired
    CommonConfigService commonConfigService;
    @Autowired
    RegionService regionService;
    @Autowired
    UserInfoService userInfoService;

    private final Logger logger = LoggerFactory.getLogger(NeedInfoController.class);
   
    @ApiOperation(value = "查看需求详情")
    @GetMapping(value= {"/selectNeedInfoDetail"},produces = "application/json;charset=utf-8")
    public APIResponse selectNeedInfoDetail(@NotNull(message = "需求id不能为空") Long id){
    	NeedInfo needInfo = needInfoService.selectDetailById(id);
    	if(needInfo != null){
	    	String stateLable = wxSysDictService.getDictLabel(needInfo.getState(), "need_state",needInfo.getState());
	    	String typeLable = wxSysDictService.getDictLabel(needInfo.getType(), "need_type",needInfo.getType());
			needInfo.setStateLabel(stateLable);
			needInfo.setTypeLabel(typeLable);
			if(!StringUtil.isEmpty(needInfo.getCity()))
			{
				Region r = regionService.selectByPrimaryKey(Integer.parseInt(needInfo.getCity()));
				if(r != null)
					needInfo.setCityLabel(r.getName());
			}
			if(!StringUtil.isEmpty(needInfo.getProvince()))
			{
				Region r = regionService.selectByPrimaryKey(Integer.parseInt(needInfo.getProvince()));
				if(r != null)
					needInfo.setProvinceLabel(r.getName());
			}
			UserInfo userInfo = userInfoService.selectUserInfoByid(needInfo.getUserInfoId().intValue());
			if(userInfo != null)
			{
				if("1".equals(userInfo.getType()))
					needInfo.setUserName(userInfo.getRealName());
				if("2".equals(userInfo.getType()))
				{
					UserInforCompany userInforCompany = userInfoService.selectUserInfoCompanyById(userInfo.getUserId());
					if(userInforCompany != null)
						needInfo.setUserName(userInforCompany.getCompanyName());
				}
			}
				
    	}
    	return APIResponse.returnSuccess(needInfo);
    }
    
	@ApiOperation(value = "前端查看所有需求信息（支持模糊搜索）")
	@GetMapping(value= {"/selectAll"},produces = "application/json;charset=utf-8")
	public APIResponse selectAll(String searchKey,String type, String technicalFieldId,String province,String city,String sort,
			@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10")Integer pageSize) {
		PageInfo page = needInfoService.selectAll(type, technicalFieldId,province,city,searchKey,sort, pageNum, pageSize);
		List list = page.getList();
		if(list != null && list.size()>0)
		{
			for(int i=0;i<list.size();i++)
			{
				NeedInfo needInfo = (NeedInfo)list.get(i);
				String stateLable = wxSysDictService.getDictLabel(needInfo.getState(), "need_state",needInfo.getState());
				needInfo.setStateLabel(stateLable);
				if(!StringUtil.isEmpty(needInfo.getCity()))
				{
					Region r = regionService.selectByPrimaryKey(Integer.parseInt(needInfo.getCity()));
					if(r != null)
						needInfo.setCityLabel(r.getName());
				}
				if(!StringUtil.isEmpty(needInfo.getProvince()))
				{
					Region r = regionService.selectByPrimaryKey(Integer.parseInt(needInfo.getProvince()));
					if(r != null)
						needInfo.setProvinceLabel(r.getName());
				}
			}
		}
		return APIResponse.returnSuccess(page);
	
	}
    
   
    @ApiOperation(value = "获取需求类型")
    @GetMapping(value= {"/queryNeedType"},produces = "application/json;charset=utf-8")
	public APIResponse queryNeedType() {
			List<WxSysDict> list = wxSysDictService.selectAllType("need_type");
			if(list != null && list.size() > 0)
			{
				List rlist = new ArrayList();
				for(int i=0;i<list.size();i++)
				{
					WxSysDict dict = list.get(i);
					Map dmap = new HashMap();
					dmap.put("id",dict.getValue());
					dmap.put("desc",dict.getLabel());
					rlist.add(dmap);
				}
				return APIResponse.returnSuccess(rlist);
			}
			else
				return APIResponse.returnSuccess();
	}
    
    @ApiOperation(value = "获取技术领域")
    @GetMapping(value= {"/queryTechnicalField"},produces = "application/json;charset=utf-8")
	public APIResponse queryTechnicalField() {
    		CommonConfig commonConfig= commonConfigService.selectByPrimaryKey(2);
			if(commonConfig != null && commonConfig.getConfig() != null && commonConfig.getConfig().size() > 0)
			{
				List tlist = new ArrayList();
				for(int i=0;i<commonConfig.getConfig().size();i++)
				{
					Map tmap = new HashMap() ;
					Map cmap = (Map)commonConfig.getConfig().get(i);
					
					tmap.put("id",cmap.get("id"));
					tmap.put("desc",cmap.get("desc"));
					tlist.add(tmap);
				}
				return APIResponse.returnSuccess(tlist);
			}
			else
				return APIResponse.returnSuccess();
	}
    
    @ApiOperation(value = "查看自己发布的需求信息")
    @SysLog(value = "查看本人需求列表",type = "需求")
    @RequiresPermissions("web:demand:list")
    @GetMapping(value= {"/selectAllByMine"},produces = "application/json;charset=utf-8")
    public APIResponse selectAllByMine(String searchKey,@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10")Integer pageSize) {
    	PageInfo page = needInfoService.selectAllByMine(ShiroUtils.getWebUserId(),searchKey,pageNum,pageSize);
    	List list = page.getList();
		if(list != null && list.size()>0)
		{
			for(int i=0;i<list.size();i++)
			{
				NeedInfo needInfo = (NeedInfo)list.get(i);
				String stateLable = wxSysDictService.getDictLabel(needInfo.getState(), "need_state",needInfo.getState());
				needInfo.setStateLabel(stateLable);
				if(!StringUtil.isEmpty(needInfo.getCity()))
				{
					Region r = regionService.selectByPrimaryKey(Integer.parseInt(needInfo.getCity()));
					if(r != null)
						needInfo.setCityLabel(r.getName());
				}
				if(!StringUtil.isEmpty(needInfo.getProvince()))
				{
					Region r = regionService.selectByPrimaryKey(Integer.parseInt(needInfo.getProvince()));
					if(r != null)
						needInfo.setProvinceLabel(r.getName());
				}
			}
		}
    	return APIResponse.returnSuccess(page);
    }
    @ApiOperation(value = "查看自己发布的需求详情")
    @SysLog(value = "查看本人需求详情",type = "需求")
    @RequiresPermissions("web:demand:info")
    @GetMapping(value= {"/selectNeedInfoDetailByMine"},produces = "application/json;charset=utf-8")
    public APIResponse selectNeedInfoDetailByMine(@NotNull(message = "需求id不能为空") Long id){
    	NeedInfo needInfo = needInfoService.selectDetailById(id);
    	if(needInfo != null && needInfo.getUserInfoId() == ShiroUtils.getWebUserId()){
	    	String stateLable = wxSysDictService.getDictLabel(needInfo.getState(), "need_state",needInfo.getState());
	    	String typeLable = wxSysDictService.getDictLabel(needInfo.getType(), "need_type",needInfo.getType());
			needInfo.setStateLabel(stateLable);
			needInfo.setTypeLabel(typeLable);
			if(!StringUtil.isEmpty(needInfo.getCity()))
			{
				Region r = regionService.selectByPrimaryKey(Integer.parseInt(needInfo.getCity()));
				if(r != null)
					needInfo.setCityLabel(r.getName());
			}
			if(!StringUtil.isEmpty(needInfo.getProvince()))
			{
				Region r = regionService.selectByPrimaryKey(Integer.parseInt(needInfo.getProvince()));
				if(r != null)
					needInfo.setProvinceLabel(r.getName());
			}
			UserInfo userInfo = userInfoService.selectUserInfoByid(needInfo.getUserInfoId().intValue());
			if(userInfo != null)
			{
				if("1".equals(userInfo.getType()))
					needInfo.setUserName(userInfo.getRealName());
				if("2".equals(userInfo.getType()))
				{
					UserInforCompany userInforCompany = userInfoService.selectUserInfoCompanyById(userInfo.getUserId());
					if(userInforCompany != null)
						needInfo.setUserName(userInforCompany.getCompanyName());
				}
			}
				
    	}
    	return APIResponse.returnSuccess(needInfo);
    }
    @ApiOperation(value = "发布需求")
    @SysLog(value = "发布需求",type = "需求")
    @RequiresPermissions("web:demand:save")
    @PostMapping("/addNeedInfo")
    public APIResponse addNeedInfo(NeedInfo needInfo){
    	if(ShiroUtils.getWebUserId() == null || needInfo.getUserInfoId()==0 
    			|| StringUtil.isEmpty(needInfo.getTitle()) || StringUtil.isEmpty(needInfo.getType())
    			|| StringUtil.isEmpty(needInfo.getTechnicalFieldId()) || StringUtil.isEmpty(needInfo.getTechnicalFieldDesc())
    			|| StringUtil.isEmpty(needInfo.getNote()))
   		 return APIResponse.returnFail(CodeMsg.BIND_ERROR);
    	needInfo.setCreateBy(ShiroUtils.getWebUserId());
    	needInfo.setState("0");
        if(needInfoService.add(needInfo)){
            return APIResponse.returnSuccess("添加成功");
        }else{
            return APIResponse.returnFail(CodeMsg.SERVER_ERROR);
        }
    }
   
    @ApiOperation(value = "编辑需求")
    @SysLog(value = "修改需求",type = "需求")
    @RequiresPermissions("web:demand:update")
    @PostMapping("/updateNeedInfo")
    public APIResponse updateNeedInfo(NeedInfo needInfo){
    	if(ShiroUtils.getWebUserId() == null || needInfo.getUserInfoId()==0 
    			|| StringUtil.isEmpty(needInfo.getTitle()) || StringUtil.isEmpty(needInfo.getType())
    			|| StringUtil.isEmpty(needInfo.getTechnicalFieldId()) || StringUtil.isEmpty(needInfo.getTechnicalFieldDesc())
    			|| StringUtil.isEmpty(needInfo.getNote()))
   		 return APIResponse.returnFail(CodeMsg.BIND_ERROR);
    	needInfo.setUpdateBy(ShiroUtils.getWebUserId());
	    needInfo.setState("0");
	    if(needInfoService.update(needInfo)){
	      return APIResponse.returnSuccess("编辑成功");
	    }else{
	      return APIResponse.returnFail(CodeMsg.SERVER_ERROR);
	    }
    }
   
    @ApiOperation(value = "删除需求")
    @SysLog(value = "删除需求",type = "需求")
    @RequiresPermissions("web:demand:delete")
    @GetMapping(value= {"/deleteNeedInfo"},produces = "application/json;charset=utf-8")
    public APIResponse deleteNeedInfo(@NotNull(message = "需求主键不能为空") Long id){
    	if(ShiroUtils.getWebUserId() == null)
    		return APIResponse.returnFail(CodeMsg.BIND_ERROR);
    	if(needInfoService.delete(id, ShiroUtils.getWebUserId())){
	      return APIResponse.returnSuccess("删除成功");
	    }else{
	      return APIResponse.returnFail(CodeMsg.SERVER_ERROR);
	    }
    }
 
   
    @ApiOperation(value = "下线需求")
    @SysLog(value = "下线需求",type = "需求")
    @RequiresPermissions("web:demand:cancel")
    @GetMapping(value= {"/offlineNeedInfo"},produces = "application/json;charset=utf-8")
    public APIResponse offlineNeedInfo(@NotNull(message = "需求主键不能为空") Long id){
    	if(ShiroUtils.getWebUserId() == null)
    		return APIResponse.returnFail(CodeMsg.BIND_ERROR);
    	if(needInfoService.offline(id, ShiroUtils.getWebUserId())){
	      return APIResponse.returnSuccess("下线成功");
	    }else{
	      return APIResponse.returnFail(CodeMsg.SERVER_ERROR);
	    }
    }
}
